let Hook = require('./Hook.js')

class HookCodeFactory {
    args() {
        return this.options.args.join(',') // ['name','age'] ==> name,age
    }
    header() {
        return `var _x = this._x;`
    }
    content() {
        let code = ``
        for (let i = 0; i < this.options.taps.length; i++) {
            code += `var _fn${i} = _x[${i}];_fn${i}(${this.args()});`
        }
        return code
    }
    setup(instance, options) { // 先准备后续需要使用的数据
        this.options = options // 源码中时通过init方法实现， 当前直接挂在this上
        instance._x = options.taps.map(o => o.fn) // this._x = [f1,f2,f3]
    }
    create() { // 创建一段可执行的代码体返回
        let fn
        // fn = new Function("name, age", "var _x = this._x, var _fn0 = _x[0]; _fn0(name,age)")
        fn = new Function(
            this.args(),
            this.header() + this.content()
        )
        return fn
    }
}

let factory = new HookCodeFactory()


class SyncHook extends Hook {
    constructor(args) {
        // super关键字调用 super既可以当做函数使用，也可以当做对象使用
        super(args)
    }

    compile(options) { // 对象 { taps: [], args: [name, age] }
        factory.setup(this, options)
        return factory.create(options)
    }
}


module.exports = SyncHook